from config import cfg
import pymysql



DATABASE_HOST = cfg.readValue('DATABASE', 'host')
DATABASE_PORT = cfg.readValue('DATABASE', 'port')
DATABASE_USER = cfg.readValue('DATABASE', 'user')
DATABASE_PASSWORD = cfg.readValue('DATABASE', 'password')
DATABASE_DB = cfg.readValue('DATABASE', 'db')



# def message_storage(modul, question, answer,links, scores, user_id, insert_time):
#     # 创建数据库连接
#     db = pymysql.connect(host=DATABASE_HOST,user=DATABASE_USER,password=DATABASE_PASSWORD,db=DATABASE_DB,port=DATABASE_PORT)
#     cursor = db.cursor()
#
#     # SQL 查询语句
#     sql = "INSERT INTO all_chat_history (modul, question, answer,links, scores, user_id, insert_time) VALUES (%s,%s,%s,%s,%s,%s,%s)"
#
#     data = (modul, question, answer,links, scores,user_id, insert_time)
#
#     try:
#         # 执行SQL语句
#         cursor.execute(sql,data)
#         db.commit()
#        # return "成功"
#         print('对话内容已保存至数据库')
#     except Exception as e:
#         print("数据保存失败：", e)
#         db.rollback()
#     # 关闭数据库连接
#     db.close()


def message_storage(modul, question, answer, additional, user_id):
    # 创建数据库连接
    db = pymysql.connect(host=DATABASE_HOST, user=DATABASE_USER, password=DATABASE_PASSWORD, db=DATABASE_DB,
                         port=DATABASE_PORT)
    cursor = db.cursor()

    # SQL 查询语句
    sql = "INSERT INTO all_chat_history (modul, question, answer,additional, user_id) VALUES (%s,%s,%s,%s,%s)"

    data = (modul, question, answer, additional, user_id)

    try:
        # 执行SQL语句
        cursor.execute(sql, data)
        db.commit()
        # return "成功"
        print('对话内容已保存至数据库')
    except Exception as e:
        print("数据保存失败：", e)
        db.rollback()
    # 关闭数据库连接
    db.close()


def to_database(sql, data):
    conn = pymysql.connect(host='132.10.10.121', user='root', password='123456', db='llm', port=3306,
                           charset='utf8mb4')
    cursor = conn.cursor()
    try:
        cursor.execute(sql, data)
        conn.commit()
        results = cursor.fetchall()
        # print("操作成功")
    except Exception as e:
        print(f'Error: {e}')
        conn.rollback()
        print(f'操作失败的sql：{sql}及data：{data}')
        print("操作失败")
        results = ''
    finally:
        conn.close()
    return results









if __name__ == '__main__':
    a = message_storage('admin','gpt','123','testrre',"ss","sdsfwe","2024-01-01")
    print(a)